//
//  KKModelItem.m
//  Questionnaire
//
//  Created by leo on 16/1/26.
//  Copyright © 2016年 leo. All rights reserved.
//

#import "KKModelItem.h"

#import <objc/runtime.h>


@implementation KKModelItem

- (void)encodeWithCoder:(NSCoder*)coder {
    
    NSObject *targetObject = self;
    
    while (targetObject.class != [NSObject class]) {
        
        unsigned int count = 0;
        //成员变量
        Ivar *ivars = class_copyIvarList(targetObject.class, &count);
        
        for (int i = 0; i < count; i++) {
            
            Ivar ivar = ivars[i];
            
            //  变量名称
            NSString *ivarName = [[NSString alloc] initWithUTF8String: ivar_getName(ivar)];
            
            //  获取值
            id value = [self valueForKey: ivarName];
            if (value != nil && ![value isKindOfClass: [NSNull class]]) {
                
                [coder encodeObject: value forKey: ivarName];
            }
        }
        free(ivars);
        
        targetObject = [targetObject.superclass new];
    }
}

- (id)initWithCoder:(NSCoder*)decoder {
    if (self = [super init]) {
        if (decoder == nil)
        {
            return self;
        }
        
        NSObject *targetObject = self;
        
        while (targetObject.class != [NSObject class]) {
            
            unsigned int count = 0;
            //成员变量
            Ivar *ivars = class_copyIvarList(targetObject.class, &count);
            
            for (int i = 0; i < count; i++) {
                
                Ivar ivar = ivars[i];
                
                //  变量名称
                NSString *ivarName = [[NSString alloc] initWithUTF8String: ivar_getName(ivar)];
                
                //  获取值
                id value = [decoder decodeObjectForKey: ivarName];
                if (value != nil && ![value isKindOfClass: [NSNull class]]) {
                    
                    [self setValue: value forKey: ivarName];
                }
            }
            free(ivars);
            
            targetObject = [targetObject.superclass new];
        }
    }
    return self;
}

@end
